<?  include('../includes/loader.inc.php'); 

	if (!$Usuario->logged()) {
		header("Location: /admin"); exit;
	}

	$config = array (
		'title' 	=> 'Ventas',
		'modulo' 	=> 'ventas',
		'key'		=> 'id_venta',
	);

	if ($_POST['data']) {
	
		foreach ($_POST['data'] as $tabla => $campos) {
			$id_parent = $db->insert($tabla, $campos);

			foreach ($campos['productos']['id_producto'] as $k => $id_producto)
				$db->insert('ventas_productos', array(
										$config['key'] => $id_parent, 
										'id_producto' => $id_producto, 
										'cantidad' => $campos['productos']['cantidad'][$k], 
										'precio' => $campos['productos']['precio'][$k]));
		}

		// Redirecciono
		header("Location: ".(($url = $Session->get($config['modulo'].'_listado'))? $url : '/admin/'.$config['modulo'].'/'));
		exit;
	}

	// Obtengo el registro a modificar
	$row = $db->get_row("SELECT v.*, c.razon_social cliente FROM ventas v, clientes c WHERE c.id_cliente = v.id_cliente AND v.id_venta = '".$_GET['id']."'");
	$row_productos = $db->get_results("SELECT vp.*, p.producto FROM ventas_productos vp, productos p WHERE vp.id_producto = p.id_producto AND vp.id_venta = '".$_GET['id']."'");

	// Obtengo los proveedores
	if ($listado = $db->get_results("SELECT id_cliente, razon_social FROM clientes WHERE activo = 1 ORDER BY razon_social"))
		foreach ($listado as $registro)
			$clientes[$registro['id_cliente']] = $registro['razon_social'];

	// Obtengo los productos
	if ($listado = $db->get_results("SELECT id_producto, CONCAT(pc.categoria, ' > ', p.producto) producto FROM productos p, productos_categorias pc WHERE p.id_categoria = pc.id_categoria ORDER BY producto"))
		foreach ($listado as $registro)
			$productos[$registro['id_producto']] = $registro['producto'];

	$id = (int)$_GET['id'];

?>
<!DOCTYPE html>

<html>

<head>
	
	<meta charset="utf-8" />
	
	<title><?=$config['title']?></title>
	
	<!-- JQUERY -->
	<script src="/js/jquery-1.4.4.min.js"></script>	
		
	<!-- JQUERY UI -->
	<script src="/js/jquery-ui-1.8.7.custom.min.js"></script>
	<script src="/admin/js/universal.js"></script>
	<link type="text/css" href="/css/smoothness/jquery-ui-1.8.7.custom.css" rel="stylesheet" />

	<!-- CSS -->
	<link rel="stylesheet" href="/css/reset.css" type="text/css" />
	<link rel="stylesheet" href="/css/admin.css" type="text/css" />	
	<link rel="stylesheet" href="/css/customizr.css" type="text/css" />
	<link rel="stylesheet" href="/css/960.css" type="text/css" />
	
	<!-- Fonts -->
	<link rel="stylesheet" href="/css/fonts/fonts.css" type="text/css" />
	<link href='http://fonts.googleapis.com/css?family=Ubuntu' rel='stylesheet' type='text/css'>
	<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
	

	<!--[if IE]>
	<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<link rel="stylesheet" href="/css/ie.css" type="text/css" />
	<![endif]-->
	
</head>

<body class="app-classic">

	<!--<div class="login-back"></div>

	<div class="titlebar"></div>
	
	<div class="window">
	
		<div class="content">-->

			<?  include('modules/header.inc.php'); ?>

			<div class="space clear"></div>

			<div class="container" data-object="">
			
				<h2><?=($config['title'])?></h2>
				
				<div class="space clear"></div>
			
				<!-- Content -->

				<form method="post" enctype="multipart/form-data" action="<?=$PHP_SELF?>" class="edit">
					<!-- hidden -->
					<input type="hidden" name="data[<?=$config['modulo']?>][<?=$config['key']?>]" value="<?=$_GET['id']?>">
					
					<div class="legend"><h3><?=$config['title']?></h3></div>
						
					<?#	foreach ($data['update'] as $id => $update): ?>
					
						<ul class="list">

							<li>
								<p>Cliente</p>
								<p>
									<?	if ($id == 0): ?>

									<select name="data[<?=$config['modulo']?>][id_cliente]">
										<? foreach($clientes as $key => $val): ?>
											<option value="<?=$key?>" ><?=ucfirst($val)?></option>
										<? endforeach; ?>
									</select>
									<?	else: ?>
									<?=$row['cliente']?>
									<?	endif; ?>
								</p>
							</li>

							<?	if ($id > 0): ?>
							
							<li>
								<p>Fecha</p>
								<p><?=current(explode(' ', $row['ctime']))?></p>
							</li>
							
							<?	endif; ?>

						</ul>

					<div class="legend"><h3>Productos</h3></div>

						<ul class="list image-list">

						<?	if ($id == 0): ?>

							<li>
								<p>
									<select name="data[<?=$config['modulo']?>][productos][id_producto][]">
										<? foreach($productos as $key => $val): ?>
											<option value="<?=$key?>" ><?=ucfirst($val)?></option>
										<? endforeach; ?>
									</select>
								</p>
								<p>Cantidad <input type="text" name="data[<?=$config['modulo']?>][productos][cantidad][]" style="width: 50px;"></p>
								<p>Precio <input type="text" name="data[<?=$config['modulo']?>][productos][precio][]" style="width: 50px;"></p>
								<p><a href="#" class="remove-image">Quitar</a></p>
							</li>

						<?	else: ?>

							<?	foreach ($row_productos as $rp): ?>
							<li>
								<p><?=$rp['producto']?></p>
								<p>Cantidad: <?=$rp['cantidad']?></p>
								<p>Precio: $<?=$rp['precio']?></p>
							</li>
							<?	endforeach; ?>

						<?	endif; ?>
						</ul>

						<?	if ($id == 0): ?>
						<ul class="list">
							<li>
								<p></p>
								<p style="text-align: right;"><a href="#" id="add-image">Agregar otro producto</a></p>
							</li>
						</ul>
						<?	endif; ?>
					
					<?#	endforeach; ?>
						
					<div class="submits">
					
						<?	if ($id == 0): ?>
						<button type="submit" name="action" value="Guardar" class="capitalize button">Guardar</button>
						<?	endif; ?>
					</div>

				</form>

				<!-- /Content -->

				
			</div>

			<footer></footer>
		
		<!--</div>
		
	</div>-->
			
<script>

$(function() {

	obj = $('[data-object]').attr('data-object');

	$('input:visible, select:visible').first().focus();
	
	$('.buttonset').buttonset();
	
	$('input[type="radio"]', '#visual-type').bind('click', function() {
		$('body').removeClass();
		$('body').addClass($(this).attr('id'));
		setCookie('app-style', $(this).attr('id'), 100);
	});
	
	
	$('[data-textsize]').live('click', function(e) {
		e.preventDefault();
		var size = parseInt($('body').css('fontSize'));
		if ($(this).attr('data-textsize') === 'plus')
			size += 1;
		else
			size -= 1;
		$('body').css('fontSize', size);
	});

	editor('[data-role=editor]');
	
        $( ".hasDatePicker" ).datepicker({'dateFormat': 'yy-mm-dd'});

/* Common
------------------------------------------------------------------------------------------ */
	
	// Seleccionar todos los checkbox
	$('[data-action="selectall"]').click(function() {
		checkboxes = $(this).parents('ul').find('input[type="checkbox"]');
		if ($(this).attr('checked'))
			checkboxes.attr('checked', 'checked');
		else
			checkboxes.removeAttr('checked');
	});
	
	$(window).jkey('shift+n', function() {
		window.location.href = '/admin/' + obj + '/add';
	});
	

});


function setCookie(name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString()+'; path=/');
}

function editor(obj) {
	$(obj).fck({
		path: '/js/fckeditor/',
		toolbar:'SIC',
		height: 500
	});
};



</script>

</body>	
	
</html>

